//
//  HXNetWorkTool.swift
//  DemoSinaWeibo
//
//  Created by Mon on 15/11/27.
//  Copyright © 2015年 Mon. All rights reserved.
//

import UIKit

import AFNetworking

/// 请求方式枚举
enum HXNetWorkRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

/// 统一管理错误
enum HXNetWorkToolError: Int {
    case EmptyAccessToken = -1
    case EmptyUid = -2
    
    //枚举属性 --> 根据不同的成员,返回不同的值
    var description: String {
        switch self {
        case .EmptyAccessToken:
            return "AccessToken没有值"
        case .EmptyUid:
            return "Uid没有值"
        }
    }
    
    // 枚举方法 --> 根据当前类型,返回错误
    func error() -> NSError {
        return NSError(domain: "error.net", code: self.rawValue, userInfo: ["description":self.description])
    }
}

class HXNetWorkTool: AFHTTPSessionManager {

/*------------------------------------------------------------------------------------------*/
    /// 创建网络工具类单例
//oauth2/authorize?client_id="_______"&response_type="_______"&redirect_uri="________"
    
    static let sharedNetWorkTool: HXNetWorkTool = {
        //访问新浪微博基本以这个开头,故创建一个原始的url
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = HXNetWorkTool(baseURL: baseURL)
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
/*------------------------------------------------------------------------------------------*/
    // MARK: - 获取用户数据
    func loadUserInfo(finished: HXNetWorkCallback) {
//        /// 需要判断一下,参数能否拿到
//        if let access_token = HXUserAccount.loadUserAccount()?.access_token {
//            //能进来说明,有access_token
//        }
//        if let uid = HXUserAccount.loadUserAccount()?.uid {
//            //能进来说明,有uid
//        }
//        /// 用户数据请求地址
//        let urlString = "2/users/show.json"
//        /// 用户数据请求参数
//        let parameters = [
//            "access_token": access_token,
//            "uid": uid
//        ]
        // 上面方法,想拿到请求参数,需要循环嵌套
        // 为了避免嵌套,使用守卫(guard),与可选绑定相反,一般与else成对出现
//        guard let access_token = HXUserAccount.loadUserAccount()?.access_token else {
//            // 能到这里来说明access_token没有值
//            // 自定义错误通知调用者 ---> 自定义错误技巧(管理错误)
//            /*
//             domain:错误类型 --> 自定义
//             code:具体错误代码 --> 自定义: 负数
//             userInfo:附加信息 --> 错误的描述
//             */
////            let errorE = HXNetWorkToolError.EmptyAccessToken
////            let error = NSError(domain: "error.net", code: errorE.rawValue, userInfo: ["description": errorE.description])
//            let error = HXNetWorkToolError.EmptyAccessToken.error()
//            finished(result: nil, error: error)
//            return
//        }
        guard let uid = HXUserAccount.loadUserAccount()?.uid else {
            // 能到这里来说明uid没有值
            // 自定义错误通知调用者
//            let errorE = HXNetWorkToolError.EmptyUid
//            let error = NSError(domain: "error.net", code: errorE.rawValue, userInfo: ["description": errorE.description])
            let error = HXNetWorkToolError.EmptyUid.error()
            finished(result: nil, error: error)
            return
        }
        
        /// 用户数据请求地址
        let urlString = "2/users/show.json"
        /// 用户数据请求参数
//        let parameters = [
//            "access_token" : access_token,
//            "uid" : uid
//        ]
        let parameters = [
            "uid" : uid
        ]
        
        /// 使用GET发送网络请求 --- 网络工具类只加载数据,不处理数据,需要闭包调出
//        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("请求用户数据成功：\(result)")
//            finished(result: result as? [String : AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                print("请求失败：\(error)")
//                finished(result: nil, error: error)
//        }
        /// 封装一
//        requestGET(urlString, parameters: parameters, finished: finished)
        /// 封装二
        request(requestMethod: HXNetWorkRequestMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
        
    }
/*------------------------------------------------------------------------------------------*/
    // MARK: - 加载微博数据
    func loadStatus(finished: HXNetWorkCallback) {
        // 使用守卫判断是否能加载出access_token
//        guard let access_token = HXUserAccount.loadUserAccount()?.access_token else {
//            //能进来说明没有加载到access_token
//            let error = HXNetWorkToolError.EmptyAccessToken.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        // 微博数据请求
        let urlString = "2/statuses/home_timeline.json"
//        let parameters = ["access_token": access_token]
        let parameters = [String: AnyObject]()
        
//        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("微博数据请求成功")
//            finished(result: result as? [String : AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                print("微博数据请求失败")
//                finished(result: nil, error: error)
//        }
        /// 封装一
//        requestGET(urlString, parameters: parameters, finished: finished)
        /// 封装二
        request(requestMethod: HXNetWorkRequestMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
    }
    
/*------------------------------------------------------------------------------------------*/
    // MARK: - Oauth授权
        /// 申请应用时分配的AppKey
    private let client_id = "3718931686"
        /// 申请应用时分配的AppSecret
    private let client_secret = "07051f29e5d36531d2260d725d27bb83"
        /// 授权回调地址
    let redirect_uri = "http://www.baidu.com/"
    
    /// 返回授权后的URL地址 --- 显示新浪的授权登录界面
    func oauthURL() -> NSURL {
        //新浪文档提示请求方式
//https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
/*------------------------------------------------------------------------------------------*/
    // MARK: - 网络工具类加载AccessToken,只负责加载数据,使用闭包来在外部实现数据处理
    func loadAccessToken(code: String, finished: HXNetWorkCallback) {
        //获得的Access Token调用API
        let urlString = "oauth2/access_token"
        
        //设置请求的参数
        let paramters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        //发送POST请求
//        POST(urlString, parameters: paramters, success: { (_, result) -> Void in
//            print("\(result)")
//            finished(result: result as? [String : AnyObject], error: nil)
//            
//            }) { (_, error) -> Void in
//                print("\(error)")
//                //回调闭包,返回出错原因
//                finished(result: nil, error: error)
//        }
        /// 封装一
//        requestPOST(urlString, paramters: paramters, finished: finished)
        
        /// 封装二
        request(requestMethod: HXNetWorkRequestMethod.POST, urlString: urlString, parameters: paramters,needAccessToken: false, finished: finished)
        
    }
    
/*------------------------------------------------------------------------------------------*/
    
    // MARK: - 由于闭包多处调用并且相同,为了统一维护调用,为相同的闭包取个别名
    typealias HXNetWorkCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    
//    // MARK: - 封装AFNetWorking:由于多处调用AFN第三方,为了后期维护方便,需要考虑封装AFN
//    func requestGET(urlString: String, parameters: [String: AnyObject],finished: HXNetWorkCallback) {
//        
//        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("微博数据请求成功")
//            finished(result: result as? [String : AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                print("微博数据请求失败")
//                finished(result: nil, error: error)
//        }
//
//    }
//    
//    func requestPOST(urlString: String, paramters: [String: AnyObject], finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
//        POST(urlString, parameters: paramters, success: { (_, result) -> Void in
//            print("\(result)")
//            finished(result: result as? [String : AnyObject], error: nil)
//            
//            }) { (_, error) -> Void in
//                print("\(error)")
//                //回调闭包,返回出错原因
//                finished(result: nil, error: error)
//        }
//    }
    
    func request(requestMethod requestMethod: HXNetWorkRequestMethod, urlString: String, var parameters: [String: AnyObject],needAccessToken: Bool, finished: HXNetWorkCallback) {
        
        if needAccessToken {
            guard let access_token = HXUserAccount.loadUserAccount()?.access_token else {
                //能进来说明没有加载到access_token
                let error = HXNetWorkToolError.EmptyAccessToken.error()
                finished(result: nil, error: error)
                return
            }
            
            // 在参数里面拼接 access_token
            parameters["access_token"] = access_token
        }
        
        /// 成功闭包回调
        let successCallback = {(task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result as? [String : AnyObject], error: nil)
        }
        
        /// 失败闭包回调
        let failureCallback = {(task: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        /// 枚举方法选择
        switch requestMethod {
            
        case .GET:
            GET(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        case .POST:
            POST(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        }
    }
    
}
